package com.feiyangedu.sample;

import java.util.LinkedList;
import java.util.Queue;

class  TaskQueue{
	final Queue<String> queue = new LinkedList<>();

	public  synchronized void addTask(String name){
		this.queue.add(name);
		System.out.println("add "+ name + " notifyall");
		this.notifyAll();//通知所有
	}
	public  synchronized  String getTask() throws  InterruptedException{
		while (this.queue.isEmpty()){
			this.wait();// 空都 等待
		}
		System.out.println("get "+ " notify");
		return  queue.remove();
	}
}

class  WorkerThread extends  Thread{
	TaskQueue taskQueue ;

	public WorkerThread(TaskQueue taskQueue){
		this.taskQueue = taskQueue;
	}
	@Override
	public  void  run(){
		while (!isInterrupted()){
			String name ;
			try {
				name = taskQueue.getTask();
			} catch (InterruptedException e) {
				break;
			}
			String res = "Hello, " + name + "!";
			System.out.println(res);
		}
	}
}

public  class  Main{
	public static void main(String[] args) throws  Exception {
		TaskQueue taskQueue = new TaskQueue();
		WorkerThread worker = new WorkerThread(taskQueue);
		worker.start();

		// add
		for(int i=0; i<10 ;i++){
			taskQueue.addTask("boy" + i);
			Thread.sleep(1000);
		}
		worker.interrupt();
		worker.join();
		System.out.println("END");
	}
}